/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package uns.fit.gis.ui;

import java.io.ByteArrayInputStream;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import uns.fit.gis.MapDrawer;
import uns.fit.gis.Util;
import uns.fit.gis.httpconnection.MHttpConnItem;
import uns.fit.gis.httpconnection.MHttpConnection;
import uns.fit.gis.httpconnection.MHttpConnectionHandler;
import uns.fit.gis.xml.BasicHandler;
import uns.fit.gis.xml.RegisterHandler;

/**
 *
 * @author nlnngu
 */
public class RegisterForm extends Form implements CommandListener, MHttpConnectionHandler {
    private TextField imei;
    private Command registerCommand;
    private Command backCommand;
    private MapDrawer midlet;

    public RegisterForm(String title, MapDrawer midlet) {
		super(title);
		this.midlet = midlet;

		registerCommand = new Command("Đăng kí", Command.OK, 1);
		addCommand(registerCommand);
		backCommand = new Command("Quay lại", Command.BACK, 2);
		addCommand(backCommand);
		
		imei = new TextField("IMEI", Util.getIMEI(), 100, TextField.UNEDITABLE);
		append(imei);
		
		setCommandListener(this);
	}

    public void commandAction(Command command, Displayable displayable) {
        if(command == backCommand)
            midlet.showMapCanvas();
        else if(command == registerCommand) {
            if(imei.getString().length() > 0) {
                new Thread() {
                    public void run() {
                        register(imei.getString());
                    }
                }.start();
            }
        }
    }

    private void register(String imei) {
                String data = "imei=" + imei;
                MHttpConnItem item = new MHttpConnItem(0, this, Util.REGISTER_URL, false, true, data.getBytes());
                MHttpConnection conn = new MHttpConnection();
                conn.addItem(item);
                conn.start();
	}


        private SAXParserFactory factory;
	private SAXParser parser;

    public int HttpLoadCompleted(byte[] data, int errorCode, MHttpConnItem item) {
        if (data == null)
            System.out.println("NULL");
        else {
            String strXML = new String(data);
            System.out.println(strXML);
            MapDrawer.showAlert(strXML);
            try {
                factory = SAXParserFactory.newInstance();
                parser = factory.newSAXParser();

                ByteArrayInputStream bais = new ByteArrayInputStream(data);
                parser.parse(bais, new RegisterHandler());
            }
            catch(Exception e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

}
